<template>
  <el-dialog 
    v-model="visible" 
    title="全局设置" 
    :width="dialogWidth"
    :before-close="handleClose"
    @open="loadSettings"
  >
    <el-scrollbar style="height: 300px;padding-right: 15px;">
    <el-form ref="settingsForm" :model="settings" label-width="120px">

       
      <el-form-item label="项目路径">
        <el-row :gutter="10">
          <el-col :span="16">
            <el-input 
              v-model="settings.projectPath" 
              placeholder="请选择项目路径"
              readonly
            ></el-input>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" @click="selectProjectPath">
              <el-icon style="margin-right: 5px;"><folder-opened /></el-icon>
              选择路径
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
      
      <el-form-item label="导出路径">
        <el-row :gutter="10">
          <el-col :span="16">
            <el-input 
              v-model="settings.exportPath" 
              placeholder="请选择导出路径"
              readonly
            ></el-input>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" @click="selectExportPath">
              <el-icon style="margin-right: 5px;"><folder-opened /></el-icon>
              选择路径
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>

      <!-- Icon路径设置 -->
      <el-form-item label="Icon路径">
        <el-row :gutter="10">
          <el-col :span="16">
            <el-input 
              v-model="settings.iconPath" 
              placeholder="请选择图标路径"
              readonly
            ></el-input>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" @click="selectIconPath">
              <el-icon style="margin-right: 5px;"><folder-opened /></el-icon>
              选择路径
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>

      <!-- 窗口大小设置 -->
       <!-- TODO:改成绝对路径/deadsplit相对路径 -->
      <el-form-item label="TODO:icon路径类型">
        <el-select 
          v-model="settings.windowSize" 
          placeholder="开发中"
         disabled
        >
          <el-option label="小 (800x600)" value="small"></el-option>
          <el-option label="中 (1024x768)" value="medium"></el-option>
          <el-option label="大 (1280x960)" value="large"></el-option>
          <el-option label="全屏" value="fullscreen"></el-option>
        </el-select>
      </el-form-item>

      <!-- Bilibili Cookie设置 -->
      <el-form-item label="Bilibili Cookie">
        <el-input 
          v-model="settings.bilibiliCookie" 
          type="textarea" 
          :rows="4"
          placeholder="请输入Bilibili Cookie内容"
          resize="none" 
        ></el-input>
      </el-form-item>

      <!-- 错误日志查看 -->
      <el-form-item>
        <el-button 
          type="warning" 
          @click="viewErrorLogs"
          class="w-full"
        >
          <el-icon><document /></el-icon>
          查看错误日志
        </el-button>
      </el-form-item>
    </el-form>
    </el-scrollbar>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveSettings">保存设置</el-button>
    </template>

  </el-dialog>
</template>

<script setup lang="ts">
//@ts-nocheck
import { ref, onMounted, getCurrentInstance } from 'vue';
import { 
  FolderOpened, 
  Document 
} from '@element-plus/icons-vue';
import { 
  open, 
  message
} from '@tauri-apps/plugin-dialog';
import { 
  writeTextFile, 
  readTextFile, 
  exists ,
  mkdir
} from '@tauri-apps/plugin-fs';
import { resourceDir } from '@tauri-apps/api/path';
import { invoke } from '@tauri-apps/api/core';
import { ElMessageBox } from 'element-plus';

const $globalProperties=getCurrentInstance()?.appContext.config.globalProperties;
// 状态管理
const visible = ref(false);
const dialogWidth = ref('600px');
const settings = ref({
  projectPath:'',
  exportPath: '',
  iconPath: '',
  windowSize: 'medium',
  bilibiliCookie: ''
});

// 配置文件路径
let configFilePath="";
let configDirPath="";

// 初始化 - 加载已保存的设置

onMounted(async () => {
  const rDir = await resourceDir();
  configDirPath = `${rDir}/config`;
  configFilePath = `${configDirPath}/settings.json`;
  await loadSettings();
});

// 加载设置
const loadSettings = async () => {
  try {
    if (await exists(configFilePath)) {
      const savedSettings = JSON.parse(await readTextFile(configFilePath));
      settings.value = { ...settings.value, ...savedSettings };
    }else{
        if (!await exists(configDirPath)) {
          await mkdir(configDirPath, { recursive: true });
        }
      await writeTextFile(configFilePath, JSON.stringify(settings.value, null, 2));
    }
    //console.log($globalProperties?.$globalSetting)
    if($globalProperties)$globalProperties.$globalSetting.value= {...settings.value};
    //loadIconDirectory();
  } catch (error) {
    console.error('加载设置失败:', error);
    await message(`加载设置失败: ${error}`,{
      kind: 'error'
    });
  }
};
/* const loadIconDirectory= async ()=>{
    if ($globalProperties && await exists($globalProperties.$globalSetting.iconPath)) {
      const iconDirectory = $globalProperties.$globalSetting.iconPath;
      const iconFiles = await readDir(iconDirectory);
      const folders= iconFiles.filter(file=> file.isDirectory)
        .map(file=>recursiveSearchIcon(`${iconDirectory}\\${file.name}`,file.name));
      const files=iconFiles.filter(file=> file.isFile).map(file=>{return{
        directory:`${iconDirectory}\\${file.name}`,
        name:file.name
        }
      });
      //console.log(files)
      let iconMap={
        files,
        folders
      } 
      console.log(iconMap)
      return iconFiles;
    } else {
      return [];
    }
}
const recursiveSearchIcon= async (folderDir:string,name:string):Promise<any>=>{
    if (await exists(folderDir)){
        const iconDirectory =folderDir
        const iconFiles = await readDir(iconDirectory);

        const folders=iconFiles.filter(file=> file.isDirectory)
            .map(file=>recursiveSearchIcon(`${iconDirectory}\\${file.name}`,file.name));
        const files=iconFiles.filter(file=> file.isFile).map(file=>{return{
            directory:`${iconDirectory}\\${file.name}`,
            name:file.name
        }
      });
      //console.log(files)
      let iconMap={
        name,
        files,
        folders
      } 
      return iconMap;
    }else return [];
} */

// 保存设置
const saveSettings = async () => {
  try {
    if (await exists(configFilePath)) {
        await writeTextFile(configFilePath, JSON.stringify(settings.value, null, 2));
    }
    else{
        if (!await exists(configDirPath)) {
          await mkdir(configDirPath, { recursive: true });
        }
      await writeTextFile(configFilePath, JSON.stringify(settings.value, null, 2));
    }
    // 通知主进程更新窗口大小
    if (settings.value.windowSize) {
      //await invoke('set_window_size', { size: settings.value.windowSize });
    }
    if($globalProperties)$globalProperties.$globalSetting.value= {...settings.value};
    await  message(`设置已保存`,{
      kind: 'info'
    });
    visible.value = false;
  } catch (error) {
    console.error('保存设置失败:', error);
    await message(`保存设置失败: ${error}`,{
      kind: 'error'
    });
  }
};

// 选择导出路径
const selectProjectPath = async () => {
  const selected = await open({
    directory: true,
    multiple: false,
    title: '选择导出路径'
  });
  
  if (selected) {
    settings.value.projectPath = Array.isArray(selected) ? selected[0] : selected;
  }
};
// 选择导出路径
const selectExportPath = async () => {
  const selected = await open({
    directory: true,
    multiple: false,
    title: '选择导出路径'
  });
  
  if (selected) {
    settings.value.exportPath = Array.isArray(selected) ? selected[0] : selected;
  }
};

// 选择Icon路径
const selectIconPath = async () => {
  const selected = await open({
    directory: true,
    multiple: false,
    title: '选择图标路径'
  });
  
  if (selected) {
    settings.value.iconPath = Array.isArray(selected) ? selected[0] : selected;
  }
};

// 查看错误日志
const viewErrorLogs = async () => {
  ElMessage.info("正在开发中...")
  /* try {
    // 调用Tauri命令获取错误日志
    const logs = await invoke('get_error_logs');
    
    // 在新窗口中显示日志
    await invoke('open_log_window', { logs });
  } catch (error) {
    console.error('查看日志失败:', error);
    await message(`查看日志失败: ${error}`,{
      kind: 'error'
    });
  } */
};

// 打开设置窗口
const openSettings = () => {
  visible.value = true;
};
function deepEqual(obj1, obj2) {
    // 检查是否是同一对象或值
    if (obj1 === obj2) {
        return true;
    }

    // 检查是否存在 null 或 undefined
    if (obj1 == null || obj2 == null) {
        return obj1 === obj2;
    }



    

    
    // 比较数组长度
    if (Array.isArray(obj1) && Array.isArray(obj2)) {
        if (obj1.length !== obj2.length) {
            return false;
        }
        for (let i = 0; i < obj1.length; i++) {
            if (!deepEqual(obj1[i], obj2[i])) {
                return false;
            }
        }
        return true;
    }

    // 获取对象的所有键
    const keys1 = Object.keys(obj1);
    const keys2 = Object.keys(obj2);

    // 比较键长度
    if (keys1.length !== keys2.length) {
        return false;
    }

    // 比较键和值
    for (let key of keys1) {
        if (!key in obj2) {
            return false;
        }
        if (!deepEqual(obj1[key], obj2[key])) {
            return false;
        }
    }

    return true;
}
// 关闭窗口
const handleClose = () => {
   if (!deepEqual($globalProperties.$globalSetting.value,settings.value)){
  ElMessageBox.confirm(
    '设置未保存，确认关闭？',
    'Warning',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  )
    .then(() => {
      visible.value=false
    })}
    else visible.value=false;
};

// 暴露打开设置窗口的方法
defineExpose({
  openSettings
});
</script>

<style scoped>
.el-form-item {
  margin-bottom: 16px;
}

.el-button {
  margin-right: 8px;
}
::v-deep .el-textarea__inner::-webkit-scrollbar{
     width: 6px ;
     height: 6px ;

}
::v-deep .el-textarea__inner::-webkit-scrollbar-thumb {
    border-radius: 3px ;
      -moz-border-radius: 3px ;
      -webkit-border-radius: 3px ;
      background-color: #c3c3c3 ;
      cursor: pointer;
}
::v-deep .el-textarea__inner::-webkit-scrollbar-track {
    background-color: transparent ;
    
}

</style>
